package com.cljz.makepassenger.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.cljz.makepassenger.base.App;
import com.cljz.makepassenger.R;
import com.cljz.makepassenger.base.BaseActivity;
import com.cljz.makepassenger.event.CollectEvent;
import com.cljz.makepassenger.model.net.bean.ActivityListBean;
import com.cljz.makepassenger.model.net.bean.GetTypeListBean;
import com.cljz.makepassenger.present.activity.NearbyP;
import com.cljz.makepassenger.ui.ItemDecoration.GridSpacesItemDecoration;
import com.cljz.makepassenger.ui.ItemDecoration.LinearSpacesItemDecoration;
import com.cljz.makepassenger.ui.adapter.NearByListAdapter;
import com.cljz.makepassenger.ui.adapter.NearbyTagsAdapter;
import com.cljz.makepassenger.utils.L;
import com.cljz.makepassenger.utils.T;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxRadioGroup;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.event.BusProvider;
import cn.droidlover.xdroidmvp.router.Router;
import rx.functions.Action1;

/**热门活动
 * Created by apple on 2017/4/26.
 */

public class NearbyActivity extends BaseActivity<NearbyP> implements CompoundButton.OnCheckedChangeListener, NearbyTagsAdapter.OnItemClickListener, BDLocationListener, XRecyclerView.LoadingListener, NearByListAdapter.OnItemClickListener {
    @BindView(R.id.ib_nearby_back)
    ImageButton ibNearbyBack;
    @BindView(R.id.tv_nearby_search)
    TextView tvNearbySearch;
    @BindView(R.id.ib_nearby_invite)
    ImageButton ibNearbyInvite;
    @BindView(R.id.rb_distance_near)
    RadioButton rbDistanceNear;
    @BindView(R.id.rb_most_person)
    RadioButton rbMostPerson;
    @BindView(R.id.rb_time_near)
    RadioButton rbTimeNear;
    @BindView(R.id.rg_choose)
    RadioGroup rgChoose;
    //    @BindView(R.id.switch_tags)
//    Switch switchTags;
    @BindView(R.id.cb_tags)
    CheckBox cbTags;
    @BindView(R.id.rv_nearby_tags)
    RecyclerView rvNearbyTags;
    @BindView(R.id.ll_nearby_tags)
    LinearLayout llNearbyTags;
    List<GetTypeListBean.DataBean> typeList;
    @BindView(R.id.xrv_nearby_list)
    XRecyclerView xrvNearbyList;
    @BindView(R.id.fl_nearby)
    FrameLayout flNearby;
    @BindView(R.id.tv_nearby_key)
    TextView tvNearbyKey;
    @BindView(R.id.ll_nearby_search)
    LinearLayout llNearbySearch;
    private NearbyTagsAdapter nearbyTagsAdapter;
    private LocationClient mLocationClient;
    private double latitude;
    private double longitude;
    private int is_nearBy, is_popular, is_latest;
    private int page = 1;
    private String key = "";
    private boolean isLoadMore;
    private boolean isRefresh;
    private NearByListAdapter nearByListAdapter;
    private List<ActivityListBean.DataBean> activityList;
    private boolean isFirst = true;
    private String typeId = "";
    private int changePosition;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 233 && resultCode == RESULT_OK) {
            key = data.getExtras().getString("key");
            tvNearbySearch.setVisibility(View.GONE);
            tvNearbyKey.setText(key);
            tvNearbyKey.setVisibility(View.VISIBLE);
            L.e("key", key);
            xrvNearbyList.refresh();
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        initLocation();
        getP().getTypeList();
        initType();
        activityList = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        xrvNearbyList.setLayoutManager(linearLayoutManager);
        nearByListAdapter = new NearByListAdapter(this, activityList);
        xrvNearbyList.setAdapter(nearByListAdapter);
        ((SimpleItemAnimator)xrvNearbyList.getItemAnimator()).setSupportsChangeAnimations(false);
        xrvNearbyList.addItemDecoration(new LinearSpacesItemDecoration(20));
        xrvNearbyList.setLoadingMoreProgressStyle(ProgressStyle.BallClipRotate);
        xrvNearbyList.setLoadingMoreEnabled(true);
        xrvNearbyList.setPullRefreshEnabled(true);
    }

    private void initType() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        rvNearbyTags.setLayoutManager(gridLayoutManager);
        rvNearbyTags.addItemDecoration(new GridSpacesItemDecoration(30));
        nearbyTagsAdapter = new NearbyTagsAdapter(this, typeList);
        rvNearbyTags.setAdapter(nearbyTagsAdapter);
    }

    private void initLocation() {
        //声明LocationClient类  百度地图
        mLocationClient = new LocationClient(getApplicationContext());


        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备

        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系

        int span = 180000;
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的

        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要

        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps

        option.setLocationNotify(false);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果

        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”

        option.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到

        option.setIgnoreKillProcess(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死

        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集

        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要

        mLocationClient.setLocOption(option);

        //注册监听函数
        mLocationClient.registerLocationListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        llNearbyTags.setVisibility(View.GONE);
//        switchTags.setChecked(false);
        cbTags.setChecked(false);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mLocationClient.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mLocationClient.stop();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_nearby;
    }

    @Override
    protected void initListener() {
        super.initListener();
        //筛选按钮监听事件
        cbTags.setOnCheckedChangeListener(this);
//        switchTags.setOnCheckedChangeListener(this);
        RxView.clicks(llNearbyTags)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        llNearbyTags.setVisibility(View.GONE);
//                        switchTags.setChecked(false);
                        cbTags.setChecked(false);
                    }
                });

        RxView.clicks(llNearbySearch)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance())
                                .to(NearBySearchActivity.class)
                                .requestCode(233)
                                .putString("key", key)
                                .launch();
                    }
                });
        RxView.clicks(tvNearbyKey)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        tvNearbyKey.setVisibility(View.GONE);
                        key = "";
                        tvNearbySearch.setVisibility(View.VISIBLE);
                        xrvNearbyList.refresh();
                    }
                });
        RxView.clicks(ibNearbyBack)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.pop(NearbyActivity.this);
                    }
                });
        //发起邀请
        RxView.clicks(ibNearbyInvite)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance())
                                .putInt("type", EditorInvitedActivity.EDITOR_INVITE)
                                .to(EditorInvitedActivity.class)
                                .launch();
                    }
                });
        RxRadioGroup.checkedChanges(rgChoose)
                .compose(this.<Integer>bindToLifecycle())
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        is_nearBy = 0;
                        is_popular = 0;
                        is_latest = 0;
                        switch (integer) {
                            case R.id.rb_distance_near:
                                is_nearBy = 1;
                                xrvNearbyList.refresh();
                                break;
                            case R.id.rb_most_person:
                                is_popular = 1;
                                xrvNearbyList.refresh();
                                break;
                            case R.id.rb_time_near:
                                is_latest = 1;
                                xrvNearbyList.refresh();
                                break;
                        }
                    }
                });
        nearbyTagsAdapter.setOnItemClickListener(this);
        xrvNearbyList.setLoadingListener(this);
        nearByListAdapter.setOnItemClickListener(this);
    }

    @Override
    public NearbyP newP() {
        return new NearbyP();
    }


    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if (b) {
            llNearbyTags.setVisibility(View.VISIBLE);
        } else {
            llNearbyTags.setVisibility(View.GONE);
        }
    }

    @Override
    public void onTypeClick(List<GetTypeListBean.DataBean> typeList, int position) {
        this.typeList = typeList;
        if (this.typeList.get(position).getSelect()) {
            this.typeList.get(position).setSelect(false);
        } else {
            this.typeList.get(position).setSelect(true);
        }
        nearbyTagsAdapter.setTagsList(this.typeList);
        changeFiltrate();
    }

    private void changeFiltrate() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < typeList.size(); i++) {
            if (typeList.get(i).getSelect()) {
                stringBuilder.append(typeList.get(i).getId()).append(",");
            }
        }
        if (stringBuilder.length() > 0) {
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        typeId = stringBuilder.toString();
        L.e("typeId:" + typeId);
        xrvNearbyList.refresh();
    }

    @Override
    public void onLongClick(List<GetTypeListBean.DataBean> typeList, int position) {

    }

    public void getTypeListSucceed(List<GetTypeListBean.DataBean> data) {
        typeList = data;
        nearbyTagsAdapter.setTagsList(typeList);
    }

    public void getTypeListFail(String error) {

    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        //获取纬度信息
        latitude = bdLocation.getLatitude();
        //获取经度信息
        longitude = bdLocation.getLongitude();
        if (isFirst) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    xrvNearbyList.refresh();
                    showLoadingDialog();
                    isFirst = false;
                }
            });

        }
    }


    public void getActivityListSucceed(List<ActivityListBean.DataBean> dataBeanList) {
        dismissLoadingDialog();
        if (isLoadMore) {
            xrvNearbyList.loadMoreComplete();
            if (dataBeanList.size() == 0) {
                xrvNearbyList.setNoMore(true);
            } else {
//                activityList.addAll(dataBeanList);
//                nearByListAdapter.setData(activityList);
                nearByListAdapter.addData(dataBeanList);
            }
            isLoadMore = false;
        } else if (isRefresh) {
            activityList.clear();
            activityList = dataBeanList;
            nearByListAdapter.setData(activityList);
            xrvNearbyList.refreshComplete();
            isRefresh = false;
        }
    }

    public void getActivityListFail(String error) {
        dismissLoadingDialog();
        T.getInstance().showShort(error);
    }

    @Override
    public void onRefresh() {
        page = 1;
        isRefresh = true;
        getNearbyList();
    }

    @Override
    public void onLoadMore() {
        page++;
        L.e("page", page + "::lalalalla::" + activityList.size());
        isLoadMore = true;
        getNearbyList();
    }

    private void getNearbyList() {
        xrvNearbyList.setNoMore(false);
        L.e("1_net", is_nearBy, is_popular, is_latest, page, key, latitude, longitude, typeId);
        getP().getActivityList(is_nearBy, is_popular, is_latest, page, key, latitude, longitude, typeId);
    }


    @Override
    public void onClick(List<ActivityListBean.DataBean> activityList, int position) {
        Router.newIntent((Activity) App.getInstance()).to(InvitationLetterActivity.class).putInt("type", InvitationLetterActivity.ACTIVITY).putString("id", activityList.get(position).getId()).launch();

    }

    @Override
    public void onCollectClick(List<ActivityListBean.DataBean> activityList, int position) {
        this.activityList = activityList;
        changePosition = position;      //下拉刷新position为0
        ActivityListBean.DataBean dataBean = activityList.get(position);
        if ("0".equals(dataBean.getIs_collection())) {
            getP().collection(dataBean.getId());
        } else {
            getP().collectionCancel(dataBean.getId());
        }
    }


    @Override
    public void onLongClick(ActivityListBean.DataBean dataBean) {

    }


    public void collectionSucceed(String msg) {
        ActivityListBean.DataBean dataBean = activityList.get(changePosition);
        dataBean.setIs_collection("1");
        activityList.set(changePosition, dataBean);
        nearByListAdapter.setDataWithChangePosition(activityList,changePosition+ 1);
        showToast(msg, R.mipmap.nearby_success);
        BusProvider.getBus().post(new CollectEvent());

    }


    public void collectionFail(String error) {
        showToast(error, R.mipmap.jinshi);


    }

    public void collectionCancelSucceed(String msg) {
        ActivityListBean.DataBean dataBean = activityList.get(changePosition);
        dataBean.setIs_collection("0");
        activityList.set(changePosition, dataBean);
        nearByListAdapter.setDataWithChangePosition(activityList,changePosition+ 1);
        showToast(msg, R.mipmap.nearby_success);
        BusProvider.getBus().post(new CollectEvent());

    }

    public void collectionCancelFail(String error) {
        showToast(error, R.mipmap.jinshi);

    }
}
